import React, { useState } from 'react';
import { Card, Select, Button, Typography, Space, Table, Row, Col, Empty } from 'antd';
import { SwapOutlined, ClearOutlined } from '@ant-design/icons';
import { useProduct } from '../context/ProductContext';
import { Product } from '../types';

const { Title, Text } = Typography;
const { Option } = Select;


const ProductSelector: React.FC = () => {
  const { state } = useProduct();
  const { categories, selectedCategoryId, selectedSubcategoryId } = state;
  
  // 本地状态：选中的两个产品
  const [product1, setProduct1] = useState<Product | null>(null);
  const [product2, setProduct2] = useState<Product | null>(null);

  // 获取当前选中的子分类
  const getCurrentSubcategory = () => {
    if (!selectedCategoryId || !selectedSubcategoryId) return null;
    
    const category = categories.find(c => c.id === selectedCategoryId);
    if (!category) return null;
    
    return category.subcategories.find(s => s.id === selectedSubcategoryId);
  };

  const currentSubcategory = getCurrentSubcategory();
  const availableProducts = currentSubcategory?.products || [];

  // 处理产品选择
  const handleProduct1Select = (productId: string | undefined) => {
    if (!productId) {
      setProduct1(null);
      return;
    }
    const product = availableProducts.find(p => p.id === productId);
    console.log(product,'product')
    setProduct1(product || null);
  };

  const handleProduct2Select = (productId: string | undefined) => {
    if (!productId) {
      setProduct2(null);
      return;
    }
    const product = availableProducts.find(p => p.id === productId);
    setProduct2(product || null);
  };

  // 清空所有选择
  const clearAllSelections = () => {
    setProduct1(null);
    setProduct2(null);
  };

  // 交换产品位置
  const swapProducts = () => {
    const temp = product1;
    setProduct1(product2);
    setProduct2(temp);
  };

  // 渲染单元格值
  const renderCellValue = (value: any, isDifferent: boolean, product?: Product,index?:number) => {
    
    // 检查是否是图片对象（Excel中的[object Object]）
    const isImageObject = value && 
                          (String(value) === '[object Object]' || 
                           (typeof value === 'object' && 
                            value !== null && 
                            typeof value.image !== 'undefined'));
    
   
    console.log(index,'index')
    // if (index==0) {
    //   console.log('🖼️ 是否为图片对象:', product);
    //   return (
    //     <div style={{ 
    //       textAlign: 'center',
    //       padding: isDifferent ? '12px' : '8px',
    //       backgroundColor: isDifferent ? '#ffebee' : 'transparent',
    //       borderRadius: isDifferent ? '6px' : '0',
    //       border: isDifferent ? '2px solid #f44336' : 'none',
    //     }}>
    //       {value && value.value && (
    //         <div style={{ 
    //           marginBottom: '8px',
    //           fontWeight: isDifferent ? 'bold' : 'normal',
    //           color: isDifferent ? '#d32f2f' : '#000000',
    //           fontSize: '13px'
    //         }}>
    //           {String(value.value)}
    //         </div>
    //       )}
    //       <img 
    //         src={product?.image} 
    //         alt={product ? product.name : '产品图片'}
    //         style={{ 
    //           maxWidth: '120px', 
    //           maxHeight: '120px',
    //           objectFit: 'contain',
    //           border: '1px solid #d9d9d9',
    //           borderRadius: '4px',
    //           backgroundColor: '#f9f9f9'
    //         }}
    //         onError={(e) => {
    //           console.error('❌ 单元格图片加载失败');
    //           e.currentTarget.style.display = 'none';
    //         }}
    //         onLoad={() => {
    //           console.log('✅ 单元格图片加载成功:', product?.name);
    //         }}
    //       />
    //     </div>
    //   );
    // }
    
    // 处理普通文本
    const text = value === null || value === undefined ? '-' : String(value);
    
    return (
      <div style={{ 
        textAlign: 'center',
        padding: isDifferent ? '8px' : '4px',
        backgroundColor: isDifferent ? '#ffebee' : 'transparent',
        borderRadius: isDifferent ? '4px' : '0',
        border: isDifferent ? '2px solid #f44336' : 'none',
        color: isDifferent ? '#d32f2f' : '#000000',
        fontWeight: isDifferent ? 'bold' : 'normal'
      }}>
        {text}
      </div>
    );
  };

  // 渲染产品标题（包含图片）
  const renderProductTitle = (product: Product) => {
    const productImage = product.image;
    console.log('🔍 产品标题 - 产品名称:', product.name);
    console.log('🖼️ 产品标题 - 获取到的图片:', productImage ? '有图片' : '无图片');
    
    return (
      <div style={{
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        textAlign: 'center'
      }}>
        {productImage && (
          <>
            <div style={{ 
              fontSize: '16px', 
              fontWeight: 'bold', 
              color: '#1890ff',
              marginBottom: '8px'
            }}>
              {product.name}
            </div>
            <div>
              <img 
                src={productImage} 
                alt={product.name}
                style={{ 
                  width: '60px', 
                  height: '60px',
                  objectFit: 'contain',
                  border: '1px solid #d9d9d9',
                  borderRadius: '4px',
                  backgroundColor: '#f9f9f9'
                }}
                onError={(e) => {
                  console.error('❌ 产品图片加载失败:', product.name);
                  e.currentTarget.style.display = 'none';
                }}
              />
            </div>
          </>
        )}
      </div>
    );
  };

  // 生成对比表格数据
  const generateComparisonData = () => {
    if (!product1 && !product2) return [];

    // 获取所有参数名称
    const allParams = new Set<string>();
    if (product1) {
      Object.keys(product1.specs).forEach(param => allParams.add(param));
    }
    if (product2) {
      Object.keys(product2.specs).forEach(param => allParams.add(param));
    }

    console.log(allParams,'allParams')
    // 生成表格数据
    return Array.from(allParams).map(param => {
      const value1 = product1?.specs[param] || '-';
      const value2 = product2?.specs[param] || '-';
      
      // 检查是否有差异
      let isDifferent = false;
      if (product1 && product2) {
        const str1 = value1 !== '-' ? String(value1).trim() : '';
        const str2 = value2 !== '-' ? String(value2).trim() : '';
        isDifferent = str1 !== str2 && str1 !== '' && str2 !== '';
      }
      console.log(value1,value2,'value1,value2')

      return {
        key: param,
        parameter: param,
        product1: value1,
        product2: value2,
        isDifferent
      };
    });
  };

  // 生成表格列配置
  const generateTableColumns = () => {
    const columns: any[] = [
      {
        title: '参数',
        dataIndex: 'parameter',
        key: 'parameter',
        width: 200,
        fixed: 'left' as const,
        render: (text: string, record: any) => (
          <Text strong style={{ 
            fontSize: '14px',
            color: record.isDifferent ? '#d32f2f' : '#000000',
            fontWeight: record.isDifferent ? 'bold' : '500'
          }}>
            {text}
          </Text>
        ),
      },
    ];
    // 产品1列
    if (product1) {
      columns.push({
        title: renderProductTitle(product1),
        dataIndex: 'product1',
        key: 'product1',
        width: 300,
        render: (value: any, record: any) => {
          return renderCellValue(value, record.isDifferent, product1);
        },
      });
    }

    // 产品2列
    if (product2) {
      columns.push({
        title: renderProductTitle(product2),
        dataIndex: 'product2',
        key: 'product2',
        width: 300,
        render: (value: any, record: any) => {
          return renderCellValue(value, record.isDifferent, product2);
        },
      });
    }

    return columns;
  };

  const comparisonData = generateComparisonData();
  const tableColumns = generateTableColumns();

  return (
    <div style={{ padding: '24px', height: 'calc(100vh - 48px)' }}>
      {/* 产品选择区域 */}
      <Card 
        title={
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Title level={3} style={{ margin: 0 }}>
              产品对比选择
              {currentSubcategory && (
                <Text type="secondary" style={{ marginLeft: '16px', fontSize: '14px' }}>
                  当前分类: {currentSubcategory.name}
                </Text>
              )}
            </Title>
            <Space>
              <Button 
                icon={<SwapOutlined />} 
                onClick={swapProducts}
                disabled={!product1 || !product2}
              >
                交换产品
              </Button>
              <Button 
                icon={<ClearOutlined />} 
                onClick={clearAllSelections}
                disabled={!product1 && !product2}
              >
                清空选择
              </Button>
            </Space>
          </div>
        }
        style={{ marginBottom: '24px' }}
      >
        {!currentSubcategory ? (
          <Empty 
            description="请在左侧选择产品分类"
            style={{ padding: '40px 0' }}
          />
        ) : (
          <Row gutter={24}>
            {/* 产品1选择 */}
            <Col span={12}>
              <div style={{ textAlign: 'center' }}>
                <Text strong style={{ display: 'block', marginBottom: '12px', fontSize: '16px' }}>
                  产品 1
                </Text>
                <Select
                  style={{ width: '100%' }}
                  placeholder="请选择产品 1"
                  value={product1?.id}
                  onChange={handleProduct1Select}
                  allowClear
                >
                  {availableProducts.map(product => (
                    <Option 
                      key={product.id} 
                      value={product.id}
                      disabled={product2?.id === product.id}
                    >
                      {product.name}
                    </Option>
                  ))}
                </Select>
              </div>
            </Col>

            {/* 产品2选择 */}
            <Col span={12}>
              <div style={{ textAlign: 'center' }}>
                <Text strong style={{ display: 'block', marginBottom: '12px', fontSize: '16px' }}>
                  产品 2
                </Text>
                <Select
                  style={{ width: '100%' }}
                  placeholder="请选择产品 2"
                  value={product2?.id}
                  onChange={handleProduct2Select}
                  allowClear
                >
                  {availableProducts.map(product => (
                    <Option 
                      key={product.id} 
                      value={product.id}
                      disabled={product1?.id === product.id}
                    >
                      {product.name}
                    </Option>
                  ))}
                </Select>
              </div>
            </Col>
          </Row>
        )}
      </Card>

      {/* 对比表格区域 */}
      {comparisonData.length > 0 && (
        <Card 
          title={
            <Title level={3} style={{ margin: 0 }}>
              产品参数对比
              {product1 && product2 && (
                <Text type="secondary" style={{ marginLeft: '16px', fontSize: '14px' }}>
                  {product1.name} vs {product2.name}
                </Text>
              )}
            </Title>
          }
        >
          <Table
            columns={tableColumns}
            dataSource={comparisonData}
            pagination={false}
            scroll={{ x: 'max-content', y: 450 }}
            size="middle"
            bordered
            className="centered-table-header"
          />
        </Card>
      )}

      {comparisonData.length === 0 && currentSubcategory && (
        <Card>
          <Empty 
            description="请选择产品进行对比"
            style={{ padding: '40px 0' }}
          />
        </Card>
      )}
    </div>
  );
};

export default ProductSelector; 